package com.jacky.flutter_screen_recording;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

import com.jacky.path_provider_ex.PathProviderExPlugin;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThumbUtils {

    private ExecutorService executorService;
    private PathProviderExPlugin plugin;
    private WeakReference<Activity> activity;

    ThumbUtils(Activity activity) {
        this.activity = new WeakReference<>(activity);
        executorService = Executors.newFixedThreadPool(5);
        plugin = new PathProviderExPlugin();
    }

    public void loadLocalFile(ImageView view, File path) {
        executorService.execute(new ThumbRunnable(view, path.getAbsolutePath()));
    }

    private class ThumbRunnable implements Runnable {
        private ImageView view;
        private String path;

        public ThumbRunnable(ImageView view, String path) {
            this.view = view;
            view.setTag(R.id.btn_shot_manager, path);
            this.path = path;
        }

        @Override
        public void run() {
            Activity activ= activity.get();
            if(activ == null) return;
            File thumbFile = new File(activ.getCacheDir(), path.hashCode() + ".jpg");
            String thumbPath = thumbFile.getAbsolutePath();
            if(!thumbFile.exists()) {
                plugin.generateImageThumb(path, thumbPath, 300, 300);
            }

            Bitmap bm = BitmapFactory.decodeFile(thumbPath);
            activ = activity.get();
            if(activ == null) return;
            activ.runOnUiThread(() -> {
                if(path.equals(view.getTag(R.id.btn_shot_manager)))
                    view.setImageBitmap(bm);
            });
        }
    }
}
